import TextEditor from '@/pages/cues/components/TextEditor';
import { recordInitAssignAccount, saveInterview, saveTravgelArrangment } from '@/services/api/api-interview-record';
import { CheckCircleOutlined, CheckCircleTwoTone, PlusOutlined } from '@ant-design/icons';
import {
    DrawerForm,
    ModalForm,
    ProCard,
    ProForm,
    ProFormCascader,
    ProFormDatePicker,
    ProFormDateRangePicker,
    ProFormDateTimeRangePicker,
    ProFormInstance,
    ProFormSelect,
    ProFormText,
    ProFormTextArea,
} from '@ant-design/pro-components';
import { Button, Cascader, Space, message } from 'antd';
import { DataNode } from 'antd/es/tree';
import { useRef, useState } from 'react';
import moment from 'moment';
import FormItem from 'antd/es/form/FormItem';
import UploadDragger from './UploadDragger';
interface AddInterviewProps {
    onRefurbish: () => void;
}
const AddInterview: React.FC<AddInterviewProps> = ({ onRefurbish }) => {
    const [modalVisit, setModalVisit] = useState(false);
    const [drawerVisit, setDrawerVisit] = useState(false);
    const formRef = useRef<ProFormInstance>();
    const [modalFormOpen, setModalFormOpenState] = useState<boolean>(false);
    /**
    * 采访单位数据
     */
    const [treeAssignOrganizationData, setTreeAssignOrganizationDataState] = useState<DataNode[]>();
    const [treeMediaData, setTreeMediaDataState] = useState<DataNode[]>();
    /**
      * 预备Tree结构数据
      * @param data
      */
    function readyTreeData(data: AdminOrganizationData.Organization[]): any {
        const treeData = new Array();
        if (data) {
            data.forEach((val) => {
                treeData.push({
                    label: val.name,
                    value: val.id,
                    disabled: val.isFolder === 1 && val.isOrganization == 0 && val.children === undefined,
                    children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
                });
            });
        }
        return treeData;
    }

    /**
     * 加载 保存 推送 单位
     */
    const loadInitSaveInterviewTreeAssignOrganization = async () => {
        try {
            const response = await recordInitAssignAccount({ type: 1 });
            if (response.code === 0) {
                setTreeAssignOrganizationDataState(readyTreeData(response.data));
            }
            const res = await recordInitAssignAccount({ type: 0 });
            if (response.code === 0) {
                setTreeMediaDataState(readyTreeData(res.data));
            }
        } catch (error) { }
    };


    return (
        <>
            <DrawerForm
                onOpenChange={(visible) => {
                    if (visible) {
                        loadInitSaveInterviewTreeAssignOrganization()
                    }
                    setDrawerVisit(visible)
                }}
                title="新建活动"
                drawerProps={{
                    destroyOnClose: true,
                }}
                layout="horizontal"
                open={drawerVisit}
                onFinish={async () => {
                    const values = formRef.current?.getFieldsValue();
                    const res = await saveInterview({
                        address: values.address,
                        assignOrganizationIds: values.assignOrganizationIds,
                        content: values.content,
                        title: values.title,
                        reporterPhone: values.reporterPhone,
                        deadlineTime: moment(values.deadlineTime).format('YYYY-MM-DD'),
                        attachments: values.articleAttachments,
                        mediaIds: values.mediaIds
                    })

                    if (res.code === 0) {
                        onRefurbish()
                        message.success('提交成功');
                        return true;
                    } else {
                        message.error("提交失败")
                        return false
                    }
                }}
                formRef={formRef}

                trigger={
                    <Button
                        key="button"
                        icon={<PlusOutlined />}
                        onClick={() => {
                        }}
                        type="primary"
                    >
                        新建活动
                    </Button>
                }
                submitter={{
                    submitButtonProps: {
                        style: {
                            display: 'none',
                        },
                    },
                    render: (props, defaultDoms) => {
                        return [
                            ...defaultDoms,
                            <Button
                                key="button_release_state_discard"
                                icon={<CheckCircleOutlined />}
                                type="primary"
                                style={{
                                    background: '#87d068',
                                }}
                                onClick={() => {
                                    const values = formRef.current?.getFieldsValue();

                                    if (
                                        values.title === undefined ||
                                        values.title.length === 0 ||
                                        values.title.trim() === ''
                                    ) {
                                        message.warning('请输入活动主题');
                                        return;
                                    }

                                    if (values.assignOrganizationIds === undefined || values.assignOrganizationIds.length === 0) {
                                        message.warning('请选择采访对象');
                                        return;
                                    }
                                    if (values.mediaIds === undefined || values.mediaIds.length === 0) {
                                        message.warning('请选择采访媒体');
                                        return;
                                    }

                                    if (
                                        values.content === undefined ||
                                        values.content.length === 0 ||
                                        values.content.trim() === ''
                                    ) {
                                        message.warning('请输入活动内容');
                                        return;
                                    }

                                    if (values.deadlineTime === undefined) {
                                        message.warning('请选择截止时间');
                                        return;
                                    }

                                    setModalFormOpenState(true);
                                }}
                            >
                                提交
                            </Button>,
                            <ModalForm
                                key={'modal_form_release_state_discard'}
                                title={
                                    <>
                                        <CheckCircleTwoTone
                                            style={{
                                                marginRight: 8,
                                            }}
                                            twoToneColor="#87d068"
                                        />
                                        确认提交
                                    </>
                                }
                                autoFocusFirstInput
                                modalProps={{
                                    destroyOnClose: true,
                                    onCancel: () => console.log('run'),
                                    width: '20%'
                                }}
                                open={modalFormOpen}
                                onOpenChange={setModalFormOpenState}
                                submitTimeout={2000}
                                submitter={{
                                    submitButtonProps: {
                                        type: 'primary',
                                        style: { background: '#87d068' },
                                    },
                                }}
                                onFinish={async (values) => {
                                    props.submit();
                                    return true;
                                }}
                            />,
                        ];
                    },
                }}
            >
                <ProFormText
                    width="xl"
                    name="title"
                    label="活动主题"
                    required
                    placeholder="请输入活动主题"
                    fieldProps={{
                        required: true
                    }}
                />
                <ProFormCascader
                    width="xl"
                    label="采访媒体"
                    name="mediaIds"
                    placeholder="选择采访媒体"
                    fieldProps={{
                        options: treeMediaData,
                        // showSearch: { filter },
                        multiple: true,
                        removeIcon: false,
                        allowClear: true,
                        maxTagCount: 'responsive',
                        showCheckedStrategy: Cascader.SHOW_CHILD,
                    }}
                />
                <ProFormCascader
                    width="xl"
                    label="采访对象"
                    name="assignOrganizationIds"
                    placeholder="选择采访对象"
                    fieldProps={{
                        options: treeAssignOrganizationData,
                        // showSearch: { filter },
                        multiple: true,
                        removeIcon: false,
                        allowClear: true,
                        maxTagCount: 'responsive',
                        showCheckedStrategy: Cascader.SHOW_CHILD,
                    }}
                />
                <ProFormDatePicker
                    name="deadlineTime"
                    width="xl"
                    label="截止时间"
                    fieldProps={{
                        disabledDate: (current) => current && current < moment().endOf('day'),
                        format: 'YYYY-MM-DD HH:mm:ss',
                    }}
                />
                {/* <ProFormText
                    name="address"
                    required
                    label="采访地址"
                    placeholder="请输入采访地址"
                    fieldProps={{
                        required: true
                    }}
                /> */}

                {/* <ProFormDateTimeRangePicker
                    name="interviewTime"
                    width='lg'
                    label="采访时间"
                    required
                    fieldProps={{
                        ranges: {
                            今日: [moment(), moment()],
                            本月: [moment().startOf('month'), moment().endOf('month')],
                            上月: [
                                moment().startOf('month').subtract(1, 'months'),
                                moment().endOf('month').subtract(1, 'months'),
                            ],
                            最近7天: [moment().subtract(6, 'days'), moment()],
                            最近60天: [moment().subtract(59, 'days'), moment()],
                            最近90天: [moment().subtract(89, 'days'), moment()],
                        },
                        format: 'YYYY-MM-DD HH:mm:ss',
                    }}
                /> */}
                <ProCard ghost>
                    <ProCard colSpan={'1'} ghost>
                        <ProForm.Item
                            name="content"
                            label="活动内容"
                        >
                            <TextEditor
                                onInit={(editor) => { }}
                                readonly={false}
                                onClick={(value) => { }}
                                defaultContent=""
                                tinyID="tinyId"
                            />
                        </ProForm.Item>
                    </ProCard>
                </ProCard>
                <FormItem
                    name="articleAttachments"
                    label={
                        <span
                            style={{
                                marginLeft: 11,
                            }}
                        >
                            附件
                        </span>
                    }
                >

                    <UploadDragger
                        style={{
                            marginLeft: '28px',
                        }}
                        onPreview={(file) => { }}
                        access={{
                            isPicture: true,
                            isVideo: true,
                            isOffice: true,
                            isOther: true,
                        }}
                        url="/interview/attachment/save"
                    />
                </FormItem>
            </DrawerForm>
        </>
    );
};

export default AddInterview;